package com.scrcu.cloud.wechat.home.endpoint.customer.service.Iml;

import cn.hutool.core.lang.hash.Hash;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.scrcu.cloud.wechat.home.endpoint.common.model.RestResponse;
import com.scrcu.cloud.wechat.home.endpoint.customer.entity.FavorInfo;
import com.scrcu.cloud.wechat.home.endpoint.customer.entity.Institution;
import com.scrcu.cloud.wechat.home.endpoint.customer.mapper.FavorInfoMapper;
import com.scrcu.cloud.wechat.home.endpoint.customer.mapper.InstMapper;
import com.scrcu.cloud.wechat.home.endpoint.customer.mapper.UserMapper;
import com.scrcu.cloud.wechat.home.endpoint.customer.vo.BookInfoPlus;
import com.scrcu.cloud.wechat.home.endpoint.customer.vo.DayInfo;
import com.scrcu.cloud.wechat.home.endpoint.customer.entity.BookInfo;
import com.scrcu.cloud.wechat.home.endpoint.customer.exception.MyException;
import com.scrcu.cloud.wechat.home.endpoint.customer.mapper.BookMapper;
import com.scrcu.cloud.wechat.home.endpoint.customer.service.IBookService;
import com.scrcu.cloud.wechat.home.endpoint.customer.utils.DateUtil;
import com.scrcu.cloud.wechat.home.endpoint.customer.dto.PreBookInfo;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scrcu.cloud.wechat.home.endpoint.common.utils.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

@Service
@Slf4j
public class BookServiceIml extends ServiceImpl<BookMapper, BookInfo>  implements IBookService {

    @Autowired
    private FavorInfoMapper favorInfoMapper;

    @Autowired
    private InstMapper instMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public RestResponse getAllDays4Month(int year, int month) {
        ArrayList<DayInfo> days = DateUtil.getAllDatesAndWeeks(year,month);
        ArrayList<DayInfo> res = new ArrayList<>();
        int startday = days.get(0).getDetail();
//        System.out.println(startday);
        for (int i = 0; i < startday-1; i++) {
            DayInfo empty = new DayInfo();
            empty.setDisplay(0);
            res.add(empty);
        }
        for (int i = 0; i < days.size(); i++) {
            res.add(days.get(i));
        }
        return RestResponse.success(res);
    }

    @Override
    public RestResponse getAllDays4Month2(int year, int month) {
        ArrayList<DayInfo> days = DateUtil.getAllDatesAndWeeks2(year,month);
        ArrayList<DayInfo> res = new ArrayList<>();
        int startday = days.get(0).getDetail();
//        System.out.println(startday);
        for (int i = 0; i < startday-1; i++) {
            DayInfo empty = new DayInfo();
            empty.setDisplay(0);
            res.add(empty);
        }
        for (int i = 0; i < days.size(); i++) {
            res.add(days.get(i));
        }
        return RestResponse.success(res);
    }

    @Override
    public RestResponse submitBook(PreBookInfo prebookInfo) {
        BookInfo bookInfo = new BookInfo();

        long uid = SnowWorkId.generateId();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMddhhmmss");
        LocalDateTime createDate = LocalDateTime.now();
        String bookid = null;
        try {
            bookid = StrUtil.padZero2(createDate.format(dateFormatter),uid,24);
        } catch (MyException e) {
            e.printStackTrace();
        }
        log.info(bookid);

        bookInfo.setBookId(bookid);bookInfo.setUid(prebookInfo.getUid());
        bookInfo.setUname(prebookInfo.getUname());bookInfo.setBtype(prebookInfo.getBtype());
        bookInfo.setBdesc(prebookInfo.getBdesc());bookInfo.setCreateTime(createDate);
        bookInfo.setDoneTime(null);

        bookInfo.setIdcard(prebookInfo.getIdcard()==null? "":prebookInfo.getIdcard());

        bookInfo.setTelnum(prebookInfo.getTelnum());
        bookInfo.setMap_id(prebookInfo.getMap_id());
        bookInfo.setAmount(prebookInfo.getAmount());

        bookInfo.setDay(prebookInfo.getDay());
        bookInfo.setMonth(prebookInfo.getMonth());
        bookInfo.setYear(prebookInfo.getYear());
        bookInfo.setStatus(0);  //状态  0 为未完成  1 为完成  2为逾期

        log.info(String.valueOf(bookInfo));
        int iflag = getBaseMapper().insert(bookInfo);  //当插入成功时返回1,失败则返回0
        if(iflag==1){
            log.info("预约成功");
            return RestResponse.success("预约成功");
        }

        return RestResponse.failed("预约失败");
    }

    @Override
    public RestResponse cancelBook(String bookid, String uid) {
        //uid用于校验
//        BookInfo bookInfo = getBaseMapper().selectById(bookid);
//        if (!bookInfo.getUid().equals(uid))
//            return RestResponse.failed("校验失败，用户权限非法");
        log.info("bookid>"+bookid);
        BookInfo bookInfo = getBaseMapper().selectById(bookid);
        log.info("bookInfo>"+bookInfo);
        int dflag = getBaseMapper().deleteById(bookInfo);
        if (dflag>=1)
            return RestResponse.success("删除成功");
        else
            return RestResponse.failed("删除失败");
    }

    @Override
    public RestResponse getBookInfo(String openid, String status) {
//        HashMap<String,Object> res = new HashMap<>();
        ArrayList<BookInfoPlus> bookinfos = new ArrayList<>();
        bookinfos = getBaseMapper().selectByOpenId4Status(openid,status);
//        res.put("bookinfos",bookinfos);
        return RestResponse.success(bookinfos);
    }

    @Override
    public RestResponse adToFavor(String mapId, String uid) {
        if(userMapper.selectById(uid)==null){
            log.warn("无效的uid");
            return RestResponse.failed();
        }

//        log.info("mapId>"+mapId);
        QueryWrapper<FavorInfo> qw = new QueryWrapper<>();
        qw.eq("uid",uid).eq("map_id",mapId);
        FavorInfo favorInfo = favorInfoMapper.selectOne(qw);
//        log.info("favorInfo>"+favorInfo);
        if (favorInfo!=null){
            int dflag = favorInfoMapper.deleteById(favorInfo);
            if (dflag>=1)
                return RestResponse.success("取消关注成功");
            else
                return RestResponse.failed("取消关注失败");
        }

        if(instMapper.selectById(mapId)==null){
            log.warn("无效的mapid");
            return RestResponse.failed();
        }


        long id = SnowWorkId.generateId();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMddhhmmss");
        LocalDateTime createDate = LocalDateTime.now();
        String fid = null;
        try {
            fid = StrUtil.padZero2(createDate.format(dateFormatter),id,24);
        } catch (MyException e) {
            e.printStackTrace();
        }
        log.info(fid);

        favorInfo = new FavorInfo();
        favorInfo.setId(fid);
        favorInfo.setMapId(mapId);
        favorInfo.setUid(uid);
//        log.info("即将添加的favorInfo>"+favorInfo);
        try{
            int iflag = favorInfoMapper.insert(favorInfo);
            if(iflag==1){
                log.info("添加收藏成功");
                return RestResponse.success("添加收藏成功");
            }
        }catch (Exception e){
            log.error("添加失败");
        }

        return RestResponse.failed("添加收藏失败");
    }

    @Override
    public RestResponse getFavorList(String uid) {
        QueryWrapper<FavorInfo> qw = new QueryWrapper<>();
        qw.eq("uid",uid);
        ArrayList<FavorInfo> list = (ArrayList<FavorInfo>) favorInfoMapper.selectList(qw);
        HashMap<String, Object> res = new HashMap<>();
        ArrayList<Institution> inslist = new ArrayList<>();
        for (FavorInfo each: list) {
            Institution institution = instMapper.selectById(each.getMapId());
            inslist.add(institution);
        }
        res.put("inslist",inslist);
        return RestResponse.success(res);
    }

    @Override
    public RestResponse judgeFavor(String mapId, String uid) {
        QueryWrapper<FavorInfo> qw = new QueryWrapper<>();
        qw.eq("uid",uid).eq("map_id",mapId);
        FavorInfo favorInfo = favorInfoMapper.selectOne(qw);
        if (favorInfo==null){
            log.info("未查到");
            return RestResponse.failed("未查到");
        }
        log.info("已查到");
        return RestResponse.success("已查到");
    }

    @Override
    public RestResponse getBooksByInst(String mapId, int year, int month, int day) {
        HashMap<String,Object> res = new HashMap<>();
        ArrayList<BookInfoPlus> bookpluslist = getBaseMapper().selectByMapId(mapId,year,month,day);

        res.put("bookinfos",bookpluslist);
        return RestResponse.success(res);
    }

}
